package com.zyz.testremoteview.widget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import androidx.core.os.BuildCompat
import com.zyz.testremoteview.R
import com.zyz.testremoteview.activity.MainActivity

class AppWidget : AppWidgetProvider() {
    /**
     * 每次小部件更新时，都会调用一次该方法
     */
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        // 可能有多个widget被激活，因此全部更新
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    /**
     * 接受广播并完成事件的分发: 分发给onEnable\onUpdate\onDeleted\onDisabled
     */
    override fun onReceive(context: Context, intent: Intent) {
        //1. 必须有, 完成事件的分发
        super.onReceive(context, intent)
        //2. 接收到自定义的ACTION
        if (intent.action == CLICK_ACTION) {
            //3. 通过RemoteViews更新UI
            val remoteViews = RemoteViews(context.packageName, R.layout.app_widget)
            remoteViews.setTextViewText(R.id.appwidget_text, "onReceive")
            val appWidgetManager = AppWidgetManager.getInstance(context)
            val componentName = ComponentName(context, AppWidget::class.java)
            appWidgetManager.updateAppWidget(componentName, remoteViews)
        }
    }

    companion object {
        const val CLICK_ACTION = "com.example.action.CLICK"

        /**
         * 更新Widget，被onUpdate调用
         */
        fun updateAppWidget(
            context: Context,
            appWidgetManager: AppWidgetManager,
            appWidgetId: Int
        ) {
            //1. 构造RemoteViews(通过布局app_widget)，并给远程TextView设置值
            val remoteViews = RemoteViews(context.packageName, R.layout.app_widget)
            remoteViews.setTextViewText(R.id.appwidget_text, "Hello")
            //2. 设置远程View的点击事件-getBroadcast获取广播
            val intent = Intent(context, MainActivity::class.java)
            intent.action = CLICK_ACTION //设置自定义ACTION
            var flags = PendingIntent.FLAG_UPDATE_CURRENT
            if (BuildCompat.isAtLeastS()) {
                flags = flags or PendingIntent.FLAG_MUTABLE
            }
            val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flags)
            remoteViews.setOnClickPendingIntent(R.id.appwidget_button, pendingIntent)
            //3. 构造WidgetManager来更新部件
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews)
        }
    }
}